<template>
  <section class="staff-form">
    <el-form ref="staff-form" :model="form" :rules="rules" label-width="80px" size="medium">
      <el-form-item label="域账号" prop="domain">
        <el-input v-model="form.domain" autocomplete="off" :disabled="userId!==null" /><el-button v-if="!userId" style="margin-left: 10px" size="small" @click.prevent="checkDomain">校验</el-button>
      </el-form-item>
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="员工性别">
        <el-radio-group v-model="form.userGender">
          <el-radio label="MALE">男</el-radio>
          <el-radio label="FEMALE">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="form.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="所属部门" prop="department">
        <el-cascader v-model="form.department" :options="department" :props="{ emitPath: false, checkStrictly: true, value: 'id', label: 'name', expandTrigger: 'hover' }" placeholder="请选择" clearable />
      </el-form-item>
      <el-form-item label="当前角色" prop="roles">
        <multiple-selector v-model="form.roles" :options="roles" placeholder="请选择" />
      </el-form-item>
      <el-form-item label="当前小组" prop="groups">
        <multiple-selector v-model="form.groups" :options="groups" placeholder="请选择" />
      </el-form-item>
      <el-form-item>
        <el-button v-debounce="handleUserData" type="primary">提 交</el-button>
        <el-button @click="reset">重 置</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
import MultipleSelector from '@/components/common/MultipleSelector';
import { getDepartmentTree } from '@/api/commonApi';
import { validPhone } from '@/utils/validate';
import { getUserList, userAdd, userUpdate, userCheck, getByIamUser, selectGroupList, selectRoleList } from '@/api/staffApi';
export default {
  name: 'StaffDataOperation',
  components: {
    MultipleSelector
  },
  data() {
    const validPhoneFunction = (rule, value, callback) => {
      if (value && !validPhone(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    return {
      form: {
        domain: '',
        name: '',
        userGender: 'MALE',
        phone: '',
        department: '',
        roles: [],
        groups: []
      },
      department: [],
      roles: [],
      groups: [],
      rules: {
        domain: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        phone: [
          { validator: validPhoneFunction, trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        roles: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        groups: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      userId: null
    };
  },
  mounted() {
    this.onGetDepartmentTree();
    this.onGetSelectRoleList();
    this.onGetSelectGroupList();
    if (this.$route.query.userId) {
      document.title = '编辑员工';
      this.$route.meta.title = '编辑员工';
      this.userId = this.CryptoJS.AES.decrypt(this.$route.query.userId, 'userId').toString(this.CryptoJS.enc.Utf8);
      this.onGetUserList();
    } else {
      document.title = '新增员工';
      this.$route.meta.title = '新增员工';
    }
  },
  methods: {
    onGetDepartmentTree() {
      getDepartmentTree().then(({ data }) => {
        this.department = [data];
      });
    },
    onGetSelectRoleList() {
      selectRoleList().then(({ data }) => {
        this.roles = data.map(item => ({ name: item.name, value: item.id }));
      });
    },
    onGetSelectGroupList() {
      selectGroupList().then(({ data }) => {
        this.groups = data.map(item => ({ name: item.name, value: item.id }));
      });
    },
    // 获取员工管理列表数据
    onGetUserList() {
      getUserList({
        userId: this.userId,
        pageNo: 1,
        pageSize: 10
      }).then(({ data }) => {
        const form = data[0];
        if (form.department) { form.department = form.department.id; }
        if (form.roles) { form.roles = form.roles.map(item => item.id); }
        if (form.groups) { form.groups = form.groups.map(item => item.id); }
        this.form = form;
      });
    },
    handleUserData() {
      this.$refs['staff-form'].validate(valid => {
        if (valid) {
          const roles = this.form.roles.map(item => ({ id: item }));
          const groups = this.form.groups.map(item => ({ id: item }));
          const department = { id: this.form.department };
          if (this.userId) {
            userUpdate({ ...this.form, roles, groups, department, userId: this.userId }).then(res => {
              this.$message.success('修改成功！');
              this.$router.push({ path: '/staff-management' });
            });
          } else {
            userAdd({ ...this.form, roles, groups, department }).then(res => {
              this.$message.success('添加成功！');
              this.$router.push({ path: '/staff-management' });
            });
          }
        }
      });
    },
    checkDomain() {
      if (this.form.domain) {
        userCheck(this.form.domain).then(res => {
          getByIamUser(this.form.domain).then(({ data }) => {
            this.$message.success('校验通过！');
            this.form.name = data.cn;
            this.form.phone = data.mobile;
          });
        });
      }
    },
    reset() {
      this.$refs['staff-form'].resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
.staff-form{
  margin: 20px;
  ::v-deep .el-input{
    width: 300px;
  }
}
</style>
